"use strict"
const PAYWEALKEY = 'payweal';
const mongodb = require('mongodb');



//验证订单,如果为定时抢购类必须自带config
exports.check = async function () {





    let id = this.get("id", 'int');
    let uid = this.get("uid", 'string');
    let cyt = this.get("cyt", 'string');

    if (!id || !uid || !cyt) {
        return false;
    }
    let paymentConfig = this.config("payment", id);
    if (!paymentConfig) {
        return false;
    }

    let paycodeConfig = this.config("paycode", paymentConfig['key']);
    if (!paycodeConfig) {
        return false;
    }

    if (!paycodeConfig.hasOwnProperty(cyt)) {
        return false;
    }


    return exports.limit.call(this, paymentConfig, uid, id);
}

exports.limit = async function (paymentConfig, uid, id) {
    if (paymentConfig['mnum']) {
        //检查每月限购
        let today = this.library("time/month");
        let query = { "uid": uid, "item": id, "time": { "$gte": today } };
        let orderModel = this.model.mongo('order', this.sid);
        let ret = await orderModel.count(query);
        if (ret >= paymentConfig['mnum']) {
            return false;
        } else {
            return true;
        }

    } else if (paymentConfig['wnum']) {
        //检查每周限购
        let today = this.library("time/week");
        let query = { "uid": uid, "item": id, "time": { "$gte": today } };
        let orderModel = this.model.mongo('order', this.sid);
        let ret = await orderModel.count(query);
        if (ret >= paymentConfig['wnum']) {
            return false;
        } else {
            return true;
        }

    } else if (paymentConfig['dnum']) {
        //检查每日限购
        let today = this.library("time/today");
        let query = { "uid": uid, "item": id, "time": { "$gte": today } };
        let orderModel = this.model.mongo('order', this.sid);
        let ret = await orderModel.count(query);
        if (ret >= paymentConfig['dnum']) {
            return false;
        } else {
            return true;
        }
    } else {
        return true;
    }
}




//创建验证订单,如果为定时抢购类必须自带config
exports.create = function () {
    let id = this.get("id", 'int');
    let uid = this.get("uid", 'string');
    let cyt = this.get("cyt", 'string');

    if (!id || !uid || !cyt) {
        return this.error("args empty", "game/local/order/create")
    }
    let paymentConfig = this.config("payment", id);
    if (!paymentConfig) {
        return this.error("config_not_exist", "payment", id);
    }

    let paycodeConfig = this.config("paycode", paymentConfig['key']);
    if (!paycodeConfig) {
        return this.error("config_not_exist", "paycode", paymentConfig['key']);
    }

    if (!paycodeConfig.hasOwnProperty(cyt)) {
        return this.error("paycode_not_exist", cyt, id);
    }

    this.updater = this.library("updater", uid, this.sid);
    this.updater.role.key("sdk", "guid", "time");


    return this.updater.data().then(() => {
        return exports.limit.call(this, paymentConfig, uid, id);
    }).then((_ok) => {
        if (_ok) {
            let data = {
                "id": id,
                "rmb": paycodeConfig[cyt],
                "cyt": cyt,
                "guid": this.updater.role.get("guid"),
                "attach": [this.updater.uid, this.updater.sid, id].join("|"),   //透传参数
                "orderid": mongodb.ObjectID().toString(),                    //订单ID
            };
            return data;
        }
        else {
            return this.error("time limit");
        }
    })
}


//充值回调发货
exports.notify = function () {
    let id = this.get('id', 'int');
    let uid = this.get('uid', 'string');
    let cyt = this.get("cyt", 'string');
    let sdk = this.get("sdk", 'string');
    let amount = this.get('amount', 'int');
    let orderid = this.get('orderid', 'string');

    if (!id || !uid || !cyt || !sdk || !orderid) {
        return this.error("args empty", "game/local/order/notify")
    }

    let paywealConfig, paymentConfig, paycodeConfig;

    paymentConfig = this.config("payment", id);
    if (!paymentConfig) {
        return this.error("config_not_exist", "payment", id);
    }

    paycodeConfig = this.config("paycode", paymentConfig['key']);
    if (!paycodeConfig) {
        return this.error("config_not_exist", "paycode", paymentConfig['key']);
    }

    if (!paycodeConfig.hasOwnProperty(cyt)) {
        return this.error("paycode_not_exist", cyt, id);
    }


    if (amount && amount != paycodeConfig[cyt]) {
        return this.error("payment_amount_error", amount, paycodeConfig[cyt]);
    }


    this.updater = this.library("updater", uid, this.sid);
    this.updater.role.key('zb', 'rmb', 'vip', 'vxp');

    let orderModel = this.model.mongo('order', this.sid);
    let orderRecord = { "_id": orderid, "sdk": sdk, "uid": uid, "cyt": cyt, "val": paycodeConfig[cyt], "item": id, "time": this.updater.time, "status": 8, "result": [] };

    this.locks = this.model.redis("locks", this.sid, 'order');
    return this.locks.start(orderid).then(ret => {
        if (ret.length > 0) {
            return order_notify_result.call(this, "locked", orderid);
        }
        return orderModel.get(orderid, ['status', 'result']);
    }).then(d => {
        if (d && d['status'] >= 8) {
            return order_notify_result.call(this, null, d);  //已经发货，防止重复
        }
        else if (d) {
            return order_notify_result.call(this, 'order_status_error', d['status']);
        }

    }).then(() => {

        return exports.limit.call(this, paymentConfig, uid, id);
    }).then(ok => {
        if (!ok) {
            return this.error("time limit");
        }
        if (!paymentConfig['first'] && !paymentConfig['tnum']) {
            return 1;
        }
        let query = { "uid": uid, "item": id };
        return orderModel.count(query).then(ret => {
            if (paymentConfig['tnum'] && ret >= paymentConfig['tnum']) {
                return order_notify_result.call(this, 'order_tnum_limit', ret);
            }
            else if (paymentConfig['first'] && ret < 1) {
                return 2;
            }
            else {
                return 1;
            }
        })

    }).
        then(P => {
            return orderModel.insert(orderRecord).then(() => P);
        }).then((P) => {
            //VIP经验 成就，每日充值
            if (paymentConfig["rmb"]) {
                this.updater.role.add('rmb', paymentConfig['rmb']);
                this.updater.role.add('vxp', paymentConfig["rmb"]);
                this.updater.daily.add('rmb', paymentConfig["rmb"]);
            }
            //每日限购购买次数
            if (paymentConfig['dnum']) {
                this.updater.daily.add('dnum', 1);
            }
            //发货
            for (let item of paymentConfig['item']) {
                if (item['id'] && item['num']) {
                    if (item['id'] == 11003) {
                        this.updater.add(11002, item['num'] * P);
                    }
                    this.updater.add(item['id'], item['num'] * P);
                }
            }
            //额外
            if (paymentConfig['bonus'] && P == 1) {
                for (let item of paymentConfig['bonusItem']) {
                    if (item['id'] && item['num']) {
                        this.updater.add(item['id'], item['num']);
                    }
                }
            }
            //月卡
            if (paymentConfig["payweal"]) {
                paywealConfig = this.config('payweal', paymentConfig["payweal"]);
                if (!paywealConfig) {
                    return this.error("config_not_exist", "paywealConfig", paymentConfig["payweal"]);
                }
                this.updater.active.key(PAYWEALKEY);
            }

            if (paymentConfig.gb.id > 0) {
                this.updater.role.key('story');
            }



            return this.updater.data();
        }).then(() => {
            if (paywealConfig) {
                let val = this.updater.active.get(PAYWEALKEY, paywealConfig['id']) || 0;
                let stime = Math.max(val, this.updater.time);
                let ttl = this.library("time/expire", stime, paywealConfig['ttl']);
                this.updater.active.set(PAYWEALKEY, paywealConfig['id'], ttl);
            }

            if (paymentConfig.gb.id > 0) {
                //金币额外增加
                //             const _story=this.updater.role.get('story');
                //             const _config=this.config('area',_story.area);
                //             if(_config){
                //                 const _gb_num=Math.floor((_config.vGold*paymentConfig.gb.per)/10000);
                //                 this.updater.add(paymentConfig.gb.id,_gb_num);
                // //                console.log(`add ${paymentConfig.gb.id} x ${_gb_num}`);
                //             }
            }

            return this.updater.save().catch(e => {
                console.error('orderNotify updater save error', JSON.stringify(orderRecord), e);
                return order_notify_result.call(this, e);
            })
        }).then(r => {
            //修改订单状态
            //算出钻石
            let _result = this.updater.cache();
            //统计充值
            let _pay_ = paymentConfig["rmb"] || 0;
            if (_pay_ > 0) {
                let today = this.library("time/today")
                let incomeModel = this.model.mongo("income", this.sid)
                incomeModel.incr(today, 'income', _pay_);
            }
            let data = { "status": 9, "result": _result };
            return orderModel.set(orderid, data).then(() => data).catch(e => {
                console.error('orderNotify status save error', JSON.stringify(orderRecord), e);
                return order_notify_result.call(this, 'orderNotify status save error', e);
            })
        }).then(data => {
            data['orderid'] = orderid;
            return order_notify_result.call(this, null, data);
        })
};


function order_notify_result(err, ret) {
    this.locks.clear();
    if (err) {
        return this.error(err, ret);
    }
    else {
        return this.success(ret);
    }
}